package com.msb.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.common.vo.CommonPageReq;
import com.msb.common.vo.CommonResult;
import com.msb.mall.core.dao.product.CategoryDao;
import com.msb.mall.core.entity.product.CategoryEntity;
import com.msb.mall.core.vo.product.Catalog2VO;
import com.msb.mall.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
//import org.apache.skywalking.apm.toolkit.trace.Tag;
//import org.apache.skywalking.apm.toolkit.trace.Tags;
//import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有的类别数据，然后将数据封装为树形结构，便于前端使用
     * 递归处理
     *
     * @return
     */
    @Override
    public List<CategoryEntity> findCategoryWithTree() {
        //1.查询所有的商品分类信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2.将商品分类信息拆解为树形结构【父子关系】
        // 第一步遍历出所有的大类 parent_cid=0
        List<CategoryEntity> list = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    //根据大类找到多有的小类  递归的方式实现
                    categoryEntity.setChildrens(getCategoryChildrens(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((entity1, entity2) -> {
                    return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
                }).collect(Collectors.toList());

        // 3. 返回处理后的商品分类列表list
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult addCategorySingle(CategoryEntity category) {
        CommonResult commonResult = new CommonResult();
        commonResult.setCode(HttpStatus.SC_OK);

        // 先判断在当前父类 下类别名称是否已存在
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", category.getName());
        paramMap.put("parentCId", category.getParentCid());
        List<CategoryEntity> oldList = categoryDao.getCategoryByCondition(paramMap);
        if(!CollectionUtils.isEmpty(oldList)) {
            commonResult.setCode(HttpStatus.SC_BAD_REQUEST);
            commonResult.setMsg("同一上级商品类别下类别名称不能重复！");
            return commonResult;
        }

        // 执行新增
        baseMapper.insert(category);

        return commonResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult updateCategory(CategoryEntity category) {
        CommonResult commonResult = new CommonResult();
        commonResult.setCode(HttpStatus.SC_OK);

        // 查询是否有效的id
        CategoryEntity id_categoryEntity = baseMapper.selectById(category.getCatId());
        if(id_categoryEntity == null || id_categoryEntity.getCatId() == null) {
            commonResult.setCode(HttpStatus.SC_BAD_REQUEST);
            commonResult.setMsg("请检查传参,[catId]无效！");
            return commonResult;
        }

        // 查询传参中的名称 在同一级别中是否已经存在
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", category.getName());
        paramMap.put("parentCId", category.getParentCid());
        paramMap.put("catLevel", category.getCatLevel());
        List<CategoryEntity> oldList = categoryDao.getCategoryByCondition(paramMap);
        if(!CollectionUtils.isEmpty(oldList)) {
            CategoryEntity oldEntity = oldList.get(0);
            // 如果旧的主键ID 和 新的主键ID 不相同，说明当前修改的类别名称已存在
            if(!oldEntity.getCatId().equals(category.getCatId())) {
                commonResult.setCode(HttpStatus.SC_BAD_REQUEST);
                commonResult.setMsg("当前级别的商品分类名称不能重复！");
                return commonResult;
            }
        }

        // 执行更新
        baseMapper.updateById(category);

        return commonResult;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

//    @Trace
    @Cacheable(value = {"catagory"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLeve1Category() {
        long start = System.currentTimeMillis();
        List<CategoryEntity> list = baseMapper.queryLeve1Category();
        log.info("查询消耗的时间:" + (System.currentTimeMillis() - start));
        return list;
    }

//    @Trace
//    @Tags({
//            @Tag(key = "getCatelog2JSON",value = "returnedObj")
//    })
    @Cacheable(value = "catagory",key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2VO>> getCatelog2JSON() {
        // 获取所有的分类数据
        List<CategoryEntity> list = baseMapper.selectList(new QueryWrapper<CategoryEntity>());
        // 获取所有的一级分类的数据
        List<CategoryEntity> leve1Category = this.queryByParenCid(list,0l);
        // 把一级分类的数据转换为Map容器 key就是一级分类的编号， value就是一级分类对应的二级分类的数据
        Map<String, List<Catalog2VO>> map = leve1Category.stream().collect(Collectors.toMap(
            key -> key.getCatId().toString(),
            value -> {
                // 根据一级分类的编号，查询出对应的二级分类的数据
                List<CategoryEntity> l2Catalogs = this.queryByParenCid(list,value.getCatId());
                List<Catalog2VO> Catalog2VOs =null;
                if(l2Catalogs != null) {
                    Catalog2VOs = l2Catalogs.stream().map(l2 -> {
                        // 需要把查询出来的二级分类的数据填充到对应的Catelog2VO中
                        Catalog2VO catalog2VO = new Catalog2VO(l2.getParentCid().toString(), null, l2.getCatId().toString(), l2.getName());
                        // 根据二级分类的数据找到对应的三级分类的信息
                        List<CategoryEntity> l3Catelogs = this.queryByParenCid(list, l2.getCatId());
                        if(l3Catelogs != null){
                            // 获取到的二级分类对应的三级分类的数据
                            List<Catalog2VO.Catalog3VO> catalog3VOS = l3Catelogs.stream().map(l3 -> {
                                Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l3.getParentCid().toString(), l3.getCatId().toString(), l3.getName());
                                return catalog3VO;
                            }).collect(Collectors.toList());
                            // 三级分类关联二级分类
                            catalog2VO.setCatalog3List(catalog3VOS);
                        }
                        return catalog2VO;
                    }).collect(Collectors.toList());
                }
                return Catalog2VOs;
            }
        ));

        return map;
    }

    private List<CategoryEntity> getCategoryChildrens(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(entity -> {
            // 根据大类找到他的直属的小类
            // Long 是 对象，用equals更好，且==有取值范围限制
//            return entity.getParentCid() == categoryEntity.getCatId();
            return entity.getParentCid().equals(categoryEntity.getCatId());
        }).map(entity -> {
            //根据这个小类递归找到对应的小小类
            entity.setChildrens(getCategoryChildrens(entity, categoryEntities));
            return entity;
        }).sorted((entity1, entity2) -> {
            return (entity1.getSort() == null ? 0 : entity1.getSort()) -
                    (entity2.getSort() == null ? 0 : entity2.getSort());
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 跟进父编号获取对应的子菜单信息
     * @param list
     * @param parentCid
     * @return
     */
    private List<CategoryEntity> queryByParenCid(List<CategoryEntity> list,Long parentCid){
        List<CategoryEntity> collect = list.stream().filter(item -> {
            return item.getParentCid().equals(parentCid);
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询所需要展示的 Category Tree
     *
     * @param commonPageReq
     * @return
     */
    private IPage<CategoryEntity> getPageCategoryTree(CommonPageReq<Map<String, Object>> commonPageReq) {
        IPage<CategoryEntity> pageReq = new Page<>(commonPageReq.getCurrPage(), commonPageReq.getPageSize());
        LambdaQueryWrapper<CategoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 查询顶级商品的分类信息
        queryWrapper.eq(CategoryEntity::getParentCid, 0);// 0 为顶级大类

        return baseMapper.selectPage(pageReq, queryWrapper);
    }

    /**
     * 225,22,2
     * @param catelogId
     * @param paths
     * @return
     */
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if(entity.getParentCid() != 0){
            findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }
}
